package com.internetCafes.spms.common.AIRecognize.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.internetCafes.spms.common.AIRecognize.handler.URLHandler;
import com.internetCafes.spms.common.AIRecognize.recognizer.impl.Pic2WordAIRecognizer;
import com.internetCafes.spms.common.CertificateTypeConstants;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.core.utils.RedisUtils;
import com.internetCafes.spms.web.certificate.vo.AIRecognizeInfo;
import com.sms.common.util.hutool.http.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LinYe
 * @date 2020/10/14
 */
@Component
public class JsonURLHandler implements URLHandler {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    Pic2WordAIRecognizer pic2WordAIRecognizer;

    /**
     * 根据url路径进行判断，进行对应处理
     *
     * @param url
     * @param filePath 证书图片路径
     * @return 智能识别实体类
     */
    @Override
    public AIRecognizeInfo handle(String url, String filePath) {
        if (url.contains(CommonConstants.QRCodeRecognizeUrlType.ZJ_GOV_WEB)) {
            if (url.contains("type=0")) {
                return handleZJGovWebQuali(url, filePath);
            } else {
                return handleZJGovWeb(url, filePath);
            }
        } else if (url.contains(CommonConstants.QRCodeRecognizeUrlType.WATER_RESOURCE_THREE_WEB)) {
            return handleWaterThreeWeb(url, filePath);
        }
        return null;
    }

    /**
     * 根据浙江政务网中请求返回json字符串进行解析。返回企业资质证书信息
     *
     * @param url
     * @param filePath 证书图片路径
     * @return 智能识别实体类
     */
    private AIRecognizeInfo handleZJGovWebQuali(String url, String filePath) {
        url = url.replace("&amp;", "&");
        int begin = url.indexOf('=');
        String param = url.substring(begin + 1);
        String json = HttpUtil.get("https://app.zjzwfw.gov.cn/zjzwfwwyw/interface/getJzyqyzzDetail.do?zzbh=" + param);
        json = json.replace("zzname", "name");
        json = json.replace("zzbh", "code");
        json = json.replace("yxqqs", "releaseDate");
        json = json.replace("yxqjz", "expireDate");
        json = json.replace("frdb", "corporateName");
        json = json.replace("zcdz", "registeredAddress");
        json = json.replace("fzjg", "releaseOrgan");
        json = json.replace("zczb", "registeredCapital");
        JSONObject jsonObject = JSON.parseObject(json);
        String baseInfo = jsonObject.getString("baseInfo");
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy年MM月dd日")
                .create();
        AIRecognizeInfo aiRecognizeInfo = gson.fromJson(baseInfo, AIRecognizeInfo.class);
        List<Integer> levels = new ArrayList<>();
        Integer level = null;
        List<String> qualificationDetails = new ArrayList<>();
        String qualificationDetail;
        JSONArray majorInfo = jsonObject.getJSONArray("majorInfo");
        for (int i = 0; i < majorInfo.size(); i++) {
            JSONObject Object = majorInfo.getJSONObject(i);
            qualificationDetail = Object.getString("tradetypeboundname") + Object.getString("tradetypename");
            qualificationDetails.add(qualificationDetail);
            String zzdj = Object.getString("zzdj");
            Map<Integer, String> descrMap = CommonConstants.QualificationLevels.descrMap;
            for (Map.Entry<Integer, String> entry : descrMap.entrySet()) {
                if (zzdj.equals(entry.getValue())) {
                    level = entry.getKey();
                    break;
                }
            }
            levels.add(level);
        }
        aiRecognizeInfo.setLevels(levels);
        aiRecognizeInfo.setQualificationDetails(qualificationDetails);
        return aiRecognizeInfo;
    }

    /**
     * 根据浙江政务网中请求返回json字符串进行解析。并根据证书类型做不同处理
     *
     * @param url
     * @param filePath 证书图片路径
     * @return 智能识别实体类
     */
    private AIRecognizeInfo handleZJGovWeb(String url, String filePath) {
        url = url.replace("&amp;", "&");
        int begin = url.indexOf('=');
        String param = url.substring(begin + 1);
        String json = HttpUtil.get("https://app.zjzwfw.gov.cn/zjzwfwwyw/interface/getJzyqyzzDetail.do?zzbh=" + param);
        if ("{}".equals(json)) {
            return null;
        }
        json = json.replace("zzbh", "certificateNo")
                .replace("yxqjz", "validityEndTime")
                .replace('年', '-')
                .replace('月', '-')
                .replace("日", "");
        if (url.contains("type=3")) {
            String result = json.replace("bzsj", "releaseTime");
            AIRecognizeInfo aiRecognizeInfo = redisUtils.fromJson(result, AIRecognizeInfo.class);
            String certificateNo = aiRecognizeInfo.getCertificateNo();
            if (certificateNo.contains("A")) {
                aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.COMPANY_MANAGER);
            } else if (certificateNo.contains("B")) {
                aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.PROJECT_MANAGER);
            } else {
                aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.SAFETY_PRODUCTION);
            }
            aiRecognizeInfo.setpIdType(CertificateTypeConstants.PIdTypeCode.THREE_CATEGORIES_PERSONNEL);
            aiRecognizeInfo.setIdType(CertificateTypeConstants.IdType.HOUSE_THREE);
            AIRecognizeInfo recognize = pic2WordAIRecognizer.recognize(filePath);
            aiRecognizeInfo.setIdCard(recognize.getIdCard());
            return aiRecognizeInfo;
        } else if (url.contains("type=2")) {
            String result = json.replace("qfrq", "releaseTime")
                    .replace("zymc", "profession");
            JSONObject jsonObject = JSONObject.parseObject(result);
            String baseInfo = jsonObject.getString("baseInfo");
            JSONArray majorInfoArray = jsonObject.getJSONArray("majorInfo");
            String majorInfo = majorInfoArray.getJSONObject(0).toJSONString();
            AIRecognizeInfo aiRecognizeInfo = redisUtils.fromJson(baseInfo, AIRecognizeInfo.class);
            AIRecognizeInfo aiRecognizeInfo1 = redisUtils.fromJson(majorInfo, AIRecognizeInfo.class);
            aiRecognizeInfo.setProfession(aiRecognizeInfo1.getProfession());
            aiRecognizeInfo.setReleaseTime(aiRecognizeInfo1.getReleaseTime());
            aiRecognizeInfo.setValidityEndTime(aiRecognizeInfo1.getValidityEndTime());
            aiRecognizeInfo.setpIdType(CertificateTypeConstants.PIdTypeCode.REGISTERED_PERSONNEL);
            aiRecognizeInfo.setIdType(CertificateTypeConstants.IdType.SECOND_CLASS_ARCHITECT);
            AIRecognizeInfo recognize = pic2WordAIRecognizer.recognize(filePath);
            aiRecognizeInfo.setIdCard(recognize.getIdCard());
            return aiRecognizeInfo;
        } else {
            return null;
        }
    }

    /**
     * 拼接url对水利三类网进行请求，获取json结果。处理后返回智能识别实体类
     *
     * @param url
     * @param filePath 图片路径
     * @return 智能识别实体类
     */
    private AIRecognizeInfo handleWaterThreeWeb(String url, String filePath) {

        Map<String, Object> param = new HashMap<>();
        param.put("pMode", "cerApprove");
        param.put("cerId", url.substring(67));
        String json = HttpUtil.post(url.substring(0, 36) + "businesspage/ElectronCer/ElectronCer.ashx", param);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String CerInfo = jsonObject.getString("CerInfo");
        CerInfo = CerInfo.replace("userName", "name")
                .replace("idcard", "idCard")
                .replace("cerNo", "certificateNo")
                .replace("statTime", "releaseTime");
        if (CerInfo.contains("\"endtime2\":\"2")) {
            CerInfo = CerInfo.replace("endtime2", "validityEndTime");
        } else if (CerInfo.contains("\"endtime1\":\"2")) {
            CerInfo = CerInfo.replace("endtime1", "validityEndTime");
        } else {
            CerInfo = CerInfo.replace("endtime", "validityEndTime");
        }
        AIRecognizeInfo aiRecognizeInfo = redisUtils.fromJson(CerInfo, AIRecognizeInfo.class);
        String certificateNo = aiRecognizeInfo.getCertificateNo();
        if (certificateNo.contains("A")) {
            aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.COMPANY_MANAGER);
        } else if (certificateNo.contains("B")) {
            aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.PROJECT_MANAGER);
        } else {
            aiRecognizeInfo.setProfession(CertificateTypeConstants.Profession.SAFETY_PRODUCTION);
        }
        aiRecognizeInfo.setpIdType(CertificateTypeConstants.PIdTypeCode.THREE_CATEGORIES_PERSONNEL);
        aiRecognizeInfo.setIdType(CertificateTypeConstants.IdType.WATER_RESOURCES);

        return aiRecognizeInfo;
    }
}
